import React, { Component } from 'react'
import { connect } from 'react-redux'
import { createContainer } from 'utils/hoc'
import ContentBox from 'components/contentBox'
import Filters from 'components/common/filters'
import CustomTable from 'components/common/table'
import { Form, message, Button, Modal } from 'antd'
import CloseOrderModal from './com/closeOrderModal'
import CustomGoodsModal from './com/customGoodsModal'
import Authorized from 'components/common/authorized'
import { widgetType, ORDER_STATUS } from 'constants'
import { getPriceFilter, dealWithLocationsearch } from 'utils/utils'
import PropTypes from 'prop-types'
import Style from './list.css'

class ListForm extends Component {
  static propTypes = {
    form: PropTypes.object,
    getOrderList: PropTypes.func,
    orderData: PropTypes.object,
    closeOrder: PropTypes.func,
    router: PropTypes.object,
    addCustomOrderLoading: PropTypes.bool,
    addCustomOrder: PropTypes.func
  }
  constructor (props) {
    super(props)
    this.state = {
      pageNo: 1,
      pageSize: 20,
      params: {},
      searchField: {},
      selectedRowKeys: [],
      showCloseOrderModal: false,
      showCustomGoodsOrder: false,
      currentOrderId: null,
      isSingleAction: true,
      selectedOrderIds: [],
      showAgreement: false,
      currentContent: ''
    }
    this.search = this.search.bind(this)
    this.reset = this.reset.bind(this)
    this.onPageChange = this.onPageChange.bind(this)
    this.onShowSizeChange = this.onShowSizeChange.bind(this)
    this.onSelectChange = this.onSelectChange.bind(this)
  }

  getFilterCols () {
    const options = Object.keys(ORDER_STATUS).map(n => {
      return {
        text: ORDER_STATUS[n],
        value: n
      }
    })

    const { status } = dealWithLocationsearch()

    return [
      {
        label: '输入搜索',
        id: 'searchField',
        widget: widgetType.input,
        placeholder: '请输入订单编号',
        span: 8
      }, {
        label: '订单状态',
        id: 'orderStatus',
        widget: widgetType.select,
        options,
        placeholder: '选择订单状态',
        span: 8,
        fieldOptions: {
          initialValue: status
        }
      }, {
        label: '收货人',
        id: 'consignee',
        widget: widgetType.input,
        placeholder: '收货人姓名/手机号码',
        span: 8
      }, {
        label: '提交时间',
        id: 'time',
        widget: widgetType.dateRangePicker,
        placeholder: '请选择时间',
        span: 8
      },
      {
        label: false,
        key: 'custom',
        widget: 'custom',
        render: () => {
          return (
            <div className={Style['custom-buttons']}>
              <Button type='primary' style={{ marginRight: 16 }} onClick={() => this.search('custom')}>查询</Button>
              <Button onClick={() => this.reset('custom')}>重置</Button>
            </div>
          )
        },
        span: 16
      }
    ]
  }

  getTableCols () {
    return [
      {
        title: '订单编号',
        dataIndex: 'orderNo',
        key: 'orderNo',
        width: 100,
        sorter: (a, b) => a.orderNo - b.orderNo
      },
      {
        title: '提交时间',
        dataIndex: 'createTime',
        key: 'createTime',
        width: 100
      },
      {
        title: '用户手机号',
        dataIndex: 'userMobile',
        key: 'userMobile',
        width: 100
      },
      {
        title: '订单金额',
        dataIndex: 'orderAmount',
        render: n => `¥${getPriceFilter(n)}`,
        key: 'orderAmount',
        width: 100,
        sorter: (a, b) => a.orderAmount - b.orderAmount

      },
      {
        title: '支付方式',
        dataIndex: 'payChannel',
        key: 'payChannel',
        width: 100
      },
      {
        title: '订单状态',
        dataIndex: 'orderStatus',
        key: 'orderStatus',
        width: 100,
        render: text => ORDER_STATUS[text]
      },
      {
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        render: (text, record) => {
          return <>
            <a className={Style['a-btn']} onClick={() => this.handleView(record.orderId)} >查看订单</a>
            <Authorized auth='ORDER:LIST:CLOSE' >
              <a className={Style['a-btn']} onClick={() => this.handleRestore(record.orderId)}>关闭订单</a>
            </Authorized>
            <a className={Style['a-btn']} onClick={() => this.handleShowAgreement(record)}>协议</a>
          </>
        },
        width: 100
      }
    ]
  }

  reset (custom) {
    if (custom === 'custom') {
      const { form } = this.props
      form.resetFields()
    }
    this.setState({
      pageNo: 1,
      pageSize: 20,
      searchField: {}
    })
    this.props.getOrderList({
      pageNo: 1,
      pageSize: 20
    })
  }

  getList = (status) => {
    const { pageNo, pageSize, searchField } = this.state
    this.props.getOrderList({
      pageNo,
      pageSize,
      orderStatus: status,
      ...searchField
    })
  }

  search (values = {}) {
    if (values === 'custom') {
      const { form } = this.props
      form.validateFields((err, items) => {
        if (!err) {
          values = items
        }
      })
    }
    if (values.time && values.time.length) {
      values.startTime = values.time[0].format('YYYY-MM-DD HH:mm:ss')
      values.endTime = values.time[1].format('YYYY-MM-DD HH:mm:ss')
    } else {
      values.startTime = ''
      values.endTime = ''
    }

    delete values.time
    this.setState({
      searchField: values
    }, () => {
      this.getList()
    })
  }

  onPageChange (pageNo, pageSize) {
    this.setState({
      pageNo,
      pageSize
    }, () => {
      this.getList()
    })
  }

  onShowSizeChange (current, pageSize) {
    this.setState({
      pageSize
    }, () => {
      this.getList()
    })
  }

  onSelectChange (selectedRowKeys, selectedRows) {
    const selectedOrderIds = selectedRows.map(n => n.orderId)
    this.setState({
      selectedRowKeys,
      selectedOrderIds
    })
  }

  componentDidMount () {
    const { status } = dealWithLocationsearch()
    this.getList(status)
  }

  componentWillReceiveProps (nextProps) {
  }

  handleView = (id) => {
    this.props.router.push(`/order/details/${id}`)
  }

  closeOrderBySelected = () => {
    const { selectedOrderIds } = this.state
    if (selectedOrderIds && selectedOrderIds.length) {
      this.setState({
        showCloseOrderModal: true,
        isSingleAction: false
      })
    } else {
      message.warning('请选择需要关闭的订单')
    }
  }

  // 关闭订单
  handleRestore (orderId) {
    this.setState({
      currentOrderId: orderId,
      showCloseOrderModal: true,
      isSingleAction: true
    })
    // this.props.restoreGoods({
    //   restoreList: [id]
    // })
  }

  confirmCloseOrderModal = form => {
    // 确认关闭订单
    const { isSingleAction } = this.state
    if (isSingleAction) {
      this.closeOrderDepend({
        orderIds: [this.state.currentOrderId],
        form
      })
    } else {
      this.closeOrderDepend({
        orderIds: this.state.selectedOrderIds,
        form
      })
    }
  }

  closeOrderDepend = ({ orderIds, form }) => {
    const { closeOrder } = this.props
    closeOrder({ orderIds, ...form }).then(() => {
      this.setState({
        showCloseOrderModal: false
      })
      this.search()
    })
  }

  handleAddCustomGoodsOrder = () => {
    this.setState({
      showCustomGoodsOrder: true
    })
  }

  confirmCustomGoodsOrder = form => {
    // TODO 接口请求
    this.props.addCustomOrder(form).then(() => {
      this.setState({
        showCustomGoodsOrder: false
      })
      this.search()
    })
  }

  handleShowAgreement = record => {
    this.setState({
      currentContent: record.agreementContent,
      showAgreement: true
    })
  }

  render () {
    const { pageNo, pageSize, selectedRowKeys, showCloseOrderModal, showCustomGoodsOrder, showAgreement, currentContent } = this.state
    const { form, orderData, addCustomOrderLoading } = this.props
    const pagination = {
      showSizeChanger: true,
      current: pageNo,
      total: orderData && orderData.total,
      onChange: this.onPageChange,
      pageSize,
      onShowSizeChange: this.onShowSizeChange
    }

    return (
      <>
        <ContentBox>
          <div className={Style['scenes-RecycleForm']}>
            <Filters
              cols={this.getFilterCols()}
              form={form}
              search={this.search}
              reset={this.reset}
              actions={false}
            >

              {/* <Button type='primary' onClick={this.closeOrderBySelected}>批量关闭</Button> */}
            </Filters>
            <div className={Style['button-wrap']}>
              <div className={Style['title']}>数据列表</div>
              <div className={Style['btns']}>
                <Button type='primary' onClick={this.handleAddCustomGoodsOrder}>新增定制订单</Button>
                <Authorized auth='ORDER:LIST:CLOSE'>
                  <Button type='primary' onClick={this.closeOrderBySelected}>关闭订单</Button>
                </Authorized>
                {/* <Button type='primary'>删除订单</Button> */}
              </div>
            </div>
            <CustomTable
              selectedRowKeys={selectedRowKeys}
              multipleSelect={this.onSelectChange}
              multiple
              loading={!orderData} columns={this.getTableCols()}
              dataSource={(orderData && orderData.list) || []}
              pagination={pagination} />
            <CloseOrderModal visible={showCloseOrderModal} onCancel={() => this.setState({ showCloseOrderModal: false })} onOk={this.confirmCloseOrderModal} />
            <CustomGoodsModal visible={showCustomGoodsOrder} confirmLoading={addCustomOrderLoading} onCancel={() => this.setState({ showCustomGoodsOrder: false })} onOk={this.confirmCustomGoodsOrder} />
            <Modal
              title='协议详情'
              visible={showAgreement}
              onCancel={() => this.setState({ showAgreement: false })}
              footer={false}
              bodyStyle={{ maxHeight: 520, overflow: 'auto' }}
            >
              <div dangerouslySetInnerHTML={{ __html: currentContent }} />
            </Modal>
          </div>

        </ContentBox>
      </>
    )
  }
}

const mapState = state => ({
  orderData: state.order.orderData,
  authorOptionsList: state.goods.authorOptionsList,
  categoryOptions: state.goods.categoryOptions,
  restoreGoodsRequest: state.goods.restoreGoodsRequest,
  addCustomOrderLoading: state.loading.effects.order.addCustomOrder
})
const mapDispatch = dispatch => ({
  getOrderList: dispatch.order.getOrderList,
  closeOrder: dispatch.order.closeOrder,
  getCategoryOptions: dispatch.goods.getCategoryOptions,
  getAuthorList: dispatch.goods.getAuthorList,
  restoreGoods: dispatch.goods.restoreGoods,
  addCustomOrder: dispatch.order.addCustomOrder
})

const List = Form.create()(ListForm)

export default createContainer(
  connect(
    mapState,
    mapDispatch
  )(List)
)
